$.fn.datepicker.dates['zh-CN'] = {
	days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
	daysShort: ["日", "一", "二", "三", "四", "五", "六"],
	daysMin: ["日", "一", "二", "三", "四", "五", "六"],
	months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
	monthsShort: ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"],
	today: "今天",
	clear: "清空",
	format: "yyyy-mm-dd",
	titleFormat: "yyyy MM", /* Leverages same syntax as 'format' */
	weekStart: 0
};
// $.fn.datepicker.dates['en'] = {
// 	days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
// 	daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
// 	daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
// 	months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
// 	monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
// 	today: "Today",
// 	clear: "Clear",
// 	format: "mm/dd/yyyy",
// 	titleFormat: "MM yyyy", /* Leverages same syntax as 'format' */
// 	weekStart: 0
// };

/**
 * DataTable封装处理
 */
sillyhatwin.ui.datatable = {
    getInstans:function(elementId,options) {
        var sillyhatDataTable;
        $(document).ready(function() {
            if (typeof(options) == "undefined") {
	            options = {};
            }
            if (typeof(options.deferRender) == "undefined") {
	            options.deferRender = true;//当处理大数据时，延迟渲染数据，有效提高Datatables处理能力
            }
            if (typeof(options.serverSide) == "undefined") {
	            options.serverSide = true;//开启服务器模式，默认是关闭
            }
            if (typeof(options.processing) == "undefined") {
	            options.processing = true;//是否开启本地分页，默认是开启
            }
            if (typeof(options.sillyhatSortColumns) == "undefined") {
                options.bSort = false;//默认不可排序
                // options.aoColumnDefs = [{"bSortable": true,"aTargets":[0]}];//不启用排序过滤
            }else if(typeof(options.sillyhatSortColumns) == "boolean") {
                options.bSort = options.sillyhatSortColumns;//全部可排序
                // options.aoColumnDefs = [{"bSortable": true,"aTargets":[0]}];//不启用排序过滤
            }else if(typeof(options.sillyhatSortColumns) == "object") {
                // options.bSort = true;//可排序
                options.aoColumnDefs = [{"bSortable": false,"aTargets":options.sillyhatSortColumns}];//启用排序过滤//[{"bSortable": false,"aTargets":[0,1,2]}]
            }
            if (typeof(options.searching) == "undefined") {
	            options.searching = false;//搜索框，默认改为不开启
            }
            if (typeof(options.lengthChange) == "undefined") {
	            options.lengthChange = true;//是否允许用户改变表格每页显示的记录数，默认是开启
            }
            if (typeof(options.paging) == "undefined") {
	            options.paging = true;//是否开启本地分页，默认是开启
            }
            // if (typeof(options.scrollY) == "undefined") {
            //     options.scrollY = "100%";//设置高
            // }
            // if (typeof(options.scrollX) == "undefined") {
            //     options.scrollX = "100%";//设置宽度
            // }
            // if (typeof(options.scrollXInner) == "undefined") {
            //     options.scrollXInner = "100%";//设置内宽度
            // }
            // if (typeof(options.scrollCollapse) == "undefined") {
            //     options.scrollCollapse = true;//是否开启DataTables的高度自适应，当数据条数不够分页数据条数的时候，插件高度是否随数据条数而改变
            // }
            // if (typeof(options.jQueryUI) == "undefined") {
            //     options.jQueryUI = false;//jquery 风格
            // }
            // if (typeof(options.autoWidth) == "undefined") {
            //     options.autoWidth = true;//是否自适应宽度
            // }
            if (typeof(options.pagingType) == "undefined") {
	            options.pagingType = "full_numbers";//simple:上一页，下一页；simple_numbers：上下+页数；full：上下首末；full_numbers上下首末+页数
            }
            if (typeof(options.lengthMenu) == "undefined") {
	            options.lengthMenu = [20,30,50,100];//更改显示记录数选项
            }
            if (typeof(options.iDisplayLength) == "undefined") {
	            options.iDisplayLength = 20;//默认显示的记录数
            }
            if (typeof(options.fnRowCallbackFormat) == "function") {
	            options.rowCallback = options.fnRowCallbackFormat;//data是后端返回的数据
            }
	        options.language = SillyHatDataTableCommon.language.zh_cn;//国际化-中文
	        if (typeof(options.dom) == "undefined") {
		        options.dom = "";
	        }
	        options.dom+="<<t><'row'<'col-sm-3'i><'col-sm-9 sillyhat-align-right'l>>fp>",//底部分页组件
	        // options.dom="<'#sillyhatDataTablesTools.top'>" +
	        //             "<<t><'row'<'col-sm-3'i><'col-sm-9 sillyhat-align-right'l>>fp>",//底部分页组件
	        // options.fnInitComplete = function () {
		     //    $("#sillyhatDataTablesTools").append('<button id="datainit" type="button" class="btn btn-primary btn-sm">增加基础数据</button>&nbsp');
		     //    $("#sillyhatDataTablesTools").append('<button type="button" class="btn btn-default btn-sm" data-toggle="modal" data-target="#myModal">添加</button>');
		     //    // $("#datainit").on("click", initData);
	        // }
	        // options.fnInitComplete = function (oSettings, json) {
		     //    $('<a href="#myModal" id="addFun" class="btn btn-primary" data-toggle="modal">新增</a>' + '&nbsp;' +
		     //      '<a href="#" class="btn btn-primary" id="editFun">修改</a> ' + '&nbsp;' +
		     //      '<a href="#" class="btn btn-danger" id="deleteFun">删除</a>' + '&nbsp;').appendTo($('.sillyhatBtnBox'));
	        // }
	        options.fnServerData = function(sSource,aoData,fnCallback){
		        if (typeof(options.fnQueryServerData) == "function") {
			        var paramsData = {};
			        for(var i = 0;i < aoData.length;i++){
				        var aoObject = aoData[i];
				        if(aoObject.name == 'draw'){
					        paramsData.draw = aoObject.value;
				        }else if(aoObject.name == 'start'){
					        paramsData.start = aoObject.value;
				        }else if(aoObject.name == 'length'){
					        paramsData.length = aoObject.value;
				        }else if(aoObject.name == 'columns'){
					        paramsData.columns = aoObject.value;
				        }else if(aoObject.name == 'order'){
					        paramsData.order = aoObject.value;
				        }else if(aoObject.name == 'search'){
					        paramsData.search = aoObject.value;
				        }
			        }
			        paramsData.searchParams = {};//初始化查询过滤参数
			        options.fnQueryServerData(paramsData,fnCallback);//执行回调函数
		        }
	        }
	        // $('#example')
	        // .on( 'order.dt',  function () { eventFired( 'Order' ); } )
	        // .on( 'search.dt', function () { eventFired( 'Search' ); } )
	        // .on( 'page.dt',   function () { eventFired( 'Page' ); } )
	        // .DataTable();
            sillyhatDataTable = $('#'+elementId).DataTable(options);//渲染表格
	        if(sillyhatwin.ui.common.isArray(options.searchDataTables)){
	        	//是数组
		        for(optionObj in options.searchDataTables){
			        if (typeof(options.searchDataTables[optionObj].eleId) == "string") {
				        $('#'+options.searchDataTables[optionObj].eleId).click(function(){
				        	var _fnSearchReturn = true;
					        if (typeof(options.searchDataTables[optionObj].fnSearchDataTables) == "function") {
						        //执行回调函数
						        _fnSearchReturn = options.searchDataTables[optionObj].fnSearchDataTables(options,sillyhatDataTable);
					        }
					        if(_fnSearchReturn){
						        sillyhatDataTable.draw();
					        }
				        });
			        }
		        }
	        }
        });
        return {
            sillyhatDataTableId : elementId,
            sillyhatDataTable:sillyhatDataTable
        };
    },
	refresh:function(elementId) {
		$("#"+elementId).DataTable().draw();
	}
}


sillyhatwin.ui.modal = {
    getInstans : function(elementId,options) {
        $(document).ready(function() {
            if (typeof(options) == "undefined") {
	            options = {};
            }
	        // $('#myModal').modal(options)
            if (typeof(options.backdrop) == "undefined") {
	            options.backdrop = false;//默认点击modal外部不关闭modal
            }
            if (typeof(options.keyboard) == "undefined") {
	            options.keyboard = false;//默认取消esc
            }
            if (typeof(options.show) == "undefined") {
	            options.show = false;//默认初始化后不显示
            }
            // if (typeof(options.remote) == "undefined") {
	         //    options.remote = "";//默认外部URL，暂不封装
            // }
	        if (typeof(options.isScroll) == "undefined") {
		        options.isScroll = true;//默认包含滚动条
	        }
	        if (typeof(options.isScroll) == "boolean") {
		        if(options.isScroll){
			        $('#'+elementId).find("[class='modal-dialog']").addClass("sillyhat-dataTables-modal-dialog");
			        $('#'+elementId).find("[class='modal-content']").addClass("sillyhat-dataTables-modal-content");
			        $('#'+elementId).find("[class='modal-header']").addClass("sillyhat-dataTables-modal-header");
			        $('#'+elementId).find("[class='modal-close']").addClass("sillyhat-dataTables-modal-close");
			        $('#'+elementId).find("[class='modal-body']").addClass("sillyhat-dataTables-modal-body");
			        $('#'+elementId).find("[class='modal-footer']").addClass("sillyhat-dataTables-modal-footer");
		        }
	        }
	        if (typeof(options.initDatepicker) == "boolean") {
            	if(options.initDatepicker){//是否初始化日期选择框
		            var datepickerArray = $('#'+elementId).find("[sillyhat-data-type='date']");//日期选择框属性标签
		            for(var dpIndex = 0; dpIndex < datepickerArray.length;dpIndex++) {
			            var item = datepickerArray[dpIndex];//获取dom组件
			            var dpOptions = {};
			            if(!item.hasAttribute("sillyhat-dp-autoclose")){
				            dpOptions.autoclose = true;//默认选择时间后自动关闭
			            }else{
				            dpOptions.autoclose = item.getAttribute("sillyhat-dp-autoclose");
			            }
			            if(!item.hasAttribute("sillyhat-dp-format")){
				            dpOptions.format = 'yyyy-mm-dd';//默认日期格式化类型
			            }else{
				            dpOptions.format = item.getAttribute("sillyhat-dp-format");//sillyhat-dp-format="yyyy-mm-dd hh:mm:ss"
			            }
			            dpOptions.language = 'zh-CN';//默认日期格式化类型
			            // if(!item.hasAttribute("sillyhat-dp-xxxxxxx")){
				         //    dpOptions.xxxxxxx = true;//默认
			            // }else{
				         //    dpOptions.xxxxxxx = item.getAttribute("sillyhat-dp-xxxxxxx");
			            // }
			            // showMonthAfterYear: true, // 月在年之后显示
				         //    changeMonth: true,   // 允许选择月份
				         //    changeYear: true,   // 允许选择年份
				         //    dateFormat:'yy-mm-dd',  // 设置日期格式
				         //    closeText:'关闭',   // 只有showButtonPanel: true才会显示出来
				         //    duration: 'fast',
				         //    showAnim:'fadeIn',
				         //    showOn:'button',   // 在输入框旁边显示按钮触发，默认为：focus。还可以设置为both
				         //    buttonImage: 'images/commons/calendar.gif',   // 按钮图标
				         //    buttonImageOnly: true,        // 不把图标显示在按钮上，即去掉按钮
				         //    buttonText:'选择日期',
				         //    showButtonPanel: true,
				         //    showOtherMonths: true,
				         //    //appendText: '(yyyy-mm-dd)',
			            $('#'+item.id).datepicker(dpOptions);//初始化datepicker
		            }
	            }
	        }
	        $('#'+elementId).modal(options);
	        // if (typeof(options.url) != "undefined") {
	        // 	var ajaxModal = {};
		     //    ajaxModal.url = options.url;
		     //    if (typeof(options.type) == "undefined") {
			 //        ajaxModal.type = "post";//默认post方式提交
		     //    }
		     //    if (typeof(options.dataType) == "undefined") {
			 //        ajaxModal.dataType = "json";
		     //    }
		     //    if (typeof(options.contentType) == "undefined") {
			 //        ajaxModal.contentType = "application/json;charset=UTF-8";
		     //    }
		     //    if (typeof(options.data) == "undefined") {
			 //        ajaxModal.data = options.data;
			 //        // JSON.stringify(paramsData)
		     //    }
		     //    ajaxModal.error = function (resp) {
			 //        alert(JSON.stringify(resp));
		     //    };
		     //    ajaxModal.success = function (result) {
			 //        if (typeof(options.fnResult) == "function") {
				//         options.fnResult(result);
			 //        }
		     //    };
             //
		     //    $.ajax(ajaxModal);
	        // }
	        if (typeof(options.showModalBefore) == "object") {
		        //封装两个参数：data  和   fnShowModalBefore
		        if (typeof(options.showModalBefore.fnShowModalBefore) == "function") {
			        //show方法后立即触发
			        $('#'+elementId).on('show.bs.modal',function(e){
				        var params = {};
				        if(sillyhatwin.ui.common.isArray(options.showModalBefore.paramsKey)){
					        for(index in options.showModalBefore.paramsKey){
						        if (typeof(options.showModalBefore.paramsKey[index]) == "string") {
							        params[options.showModalBefore.paramsKey[index]] = $(e.relatedTarget).data(options.showModalBefore.paramsKey[index])
						        }
					        }
				        }
				        options.showModalBefore.fnShowModalBefore(e,params);
			        });
			
		        }
	        }
	        if (typeof(options.showModalAfter) == "object") {
		        //封装两个参数：data  和   fnShowModalBefore
		        if (typeof(options.showModalAfter.fnShowModalAfter) == "function") {
			        //show方法后立即触发
			        $('#'+elementId).on('hide.bs.modal',function(e){
				        var params = {};
				        if(sillyhatwin.ui.common.isArray(options.showModalAfter.paramsKey)){
					        for(index in options.showModalAfter.paramsKey){
						        if (typeof(options.showModalAfter.paramsKey[index]) == "string") {
							        params[options.showModalAfter.paramsKey[index]] = $(e.relatedTarget).data(options.showModalAfter.paramsKey[index])
						        }
					        }
				        }
				        options.showModalAfter.fnShowModalAfter(e,params);
			        });
			
		        }
	        }
	        /*********以下暂未封装**************/
	        if (typeof(options.fnHideModalBefore) == "function") {
		        //隐藏前后触发
		        $('#'+elementId).on('hide.bs.modal',function(e){
			
		        });
		        fnHideModalBefore(e);
	        }
	        if (typeof(options.fnHideModalAfter) == "function") {
		        //隐藏后后触发
		        $('#'+elementId).on('hidden.bs.modal',function(e){
			
		        });
		        fnHideModalAfter(e);
	        }
	        if (typeof(options.fnLoadedModalAfter) == "function") {
		        //远端的数据源加载数据完成后触发
		        $('#'+elementId).on('loaded.bs.moda',function(e){
			
		        });
		        fnLoadedModalAfter(e);
	        }
        });
        // return {
        //     sillyhatDataTableId : elementId,
        //     sillyhatDataTable:sillyhatDataTable
        // };
    },
	close:function(elementId) {
		$('#'+elementId).modal('hide')
	},
	dataVerify:function(elementId) {
		var verifyArray = $('#'+elementId).find("[shdt-validations='true']");
		for(var index = 0;index < verifyArray.length;index++){
			var formGroupValidation = verifyArray[index];
			var value = $(formGroupValidation).val();
			// formModal[0] -> $(formModal[0])//DOM对象转换jquery对象（div->n.fn.init）
			// shdt-validations="true"//是否校验
			// shdt-required="true"   //是否必填
			// shdt-minLength="6"     //最小长度
			// shdt-maxLength="20"    //最大长度
			// shdt-msg="校验失败"      //校验提示内容
			var _required = $(formGroupValidation).attr("shdt-required")
			var _minLength = $(formGroupValidation).attr("shdt-minLength")
			var _maxLength = $(formGroupValidation).attr("shdt-maxLength")
			var _msg = $(formGroupValidation).attr("shdt-msg")
			var checkSuccess = true;
			if (typeof(_required) != "undefined" && _required == "true") {
				if(null == value || "" == value){
					checkSuccess = false;
				}else if(typeof(_minLength) != "undefined" && SillyHatDataTableCommon.isNumber(_minLength)){
					if(value.length < parseInt(_minLength)){
						checkSuccess = false;
					}
				}else if(typeof(_maxLength) != "undefined" && SillyHatDataTableCommon.isNumber(_maxLength)){
					if(value.length > parseInt(_maxLength)){
						checkSuccess = false;
					}
				}
			}
			if(checkSuccess){
				SillyHatDataTableCommon.checkSuccess($(formGroupValidation).parent().parent(),_msg);//校验成功
			}else{
				SillyHatDataTableCommon.checkError($(formGroupValidation).parent().parent(),_msg);//校验失败
			}
		}
		// <div class="col-sm-2"></div>
       // <div class="col-sm-10">
       //    <span class="help-block">Help block with success</span>
       // </div>
       // <div class="col-sm-2" style="display:none;"></div>
       //     <div class="col-sm-10" style="display:none;">
       //     <span class="help-block">Help block with success</span>
       // </div>
		return false;
	}
}

SillyHatDataTableCommon = {
    language : {
        zh_cn : {
            paginate:{
                first:'首页',
                last:'末页',
                previous:'上一页',
                next:'下一页',
                jump:"跳转"
            },
            lengthMenu:'显示 _MENU_ 条记录',
            zeroRecords:'没有检索到数据',
            info:'从 _START_ 到 _END_ /共 _TOTAL_ 条数据',
            infoEmpty:'没有检索到数据',
            search:'快速过滤：',
            processing:'正在加载数据，请稍候...',
            // "sProcessing": "<img src='/images/datatable_loading.gif'>  努力加载数据中.",
            infoFiltered:'共计 _TOTAL_ 条记录'
        }
    },
	eleReminder : function (msg) {
		return "<div class='col-sm-2'></div>"+
		            "<div class='col-sm-10'>"+
		            "<span class='help-block'>" + msg + "</span>"+
		       "</div>"
	},
	isNumber : function (checkObj) {
		var checkNumber = /^[0-9]+.?[0-9]*$/;
		return checkNumber.test(checkObj);//true:是数字
	},
	checkSuccess : function (jqueryObj,msg) {
		// jqueryObj.append(SillyHatDataTableCommon.eleReminder(msg));
		jqueryObj.addClass("has-success");
	},
	checkWarning : function (jqueryObj,msg) {
		jqueryObj.append(SillyHatDataTableCommon.eleReminder(msg));
		jqueryObj.addClass("has-warning");
	},
	checkError : function (jqueryObj,msg) {
		jqueryObj.append(SillyHatDataTableCommon.eleReminder(msg));
		jqueryObj.addClass("has-error");
	},
	
}